#pragma once 

#include <iostream>
#include <cstring>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>

class UdpClient{
  private:
    int sockfd;
    int server_port;
    std::string server_ip;
  public:
    UdpClient(std::string _ip, int _port):server_ip(_ip), server_port(_port), sockfd(-1)
    {}
    bool InitUdpClient()
    {
      sockfd = socket(AF_INET, SOCK_DGRAM, 0);
      if(sockfd == -1){
        std::cerr << "sockfd error" << std::endl;
        return false;
      }

      return true;
    }
    void Start()
    {
      struct sockaddr_in peer;
      memset(&peer, 0, sizeof(peer));
      peer.sin_family = AF_INET;
      peer.sin_port = htons(server_port);
      peer.sin_addr.s_addr = inet_addr(server_ip.c_str());
      socklen_t len = sizeof(peer);
      std::string msg;
      
      std::cout << "Please Enter #" << std::endl;
#define SIZE 128
      while(true){
        std::cin >> msg;
        //ssize_t size = write(sockfd, msg.c_str(), msg.size());
        char cmd[SIZE];
        int i = 0;
        for(i = 0; i < (int)msg.size(); i++){
          if(msg[i] != ' ')
            cmd[i] = msg[i];
          else
            cmd[i] = '-';
        }
        cmd[i] = 0;
        ssize_t size = sendto(sockfd, cmd, msg.size(), 0, (struct sockaddr*)&peer, len);
        if(size == -1){
          std::cerr << "sendto error" << std::endl;
        }

        char buffer[SIZE];
        //size = read(sockfd, buffer, sizeof(buffer) - 1);
        size = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&peer, &len);
        if(size == -1){
          std::cerr << "recvfrom error" << std::endl;
        }

        buffer[size] = 0;
        std::cout << "Server get->" << buffer << std::endl;
      }
    }
    ~UdpClient(){}
};
